package com.hzd.web;

import ablaze.framework.api.result.ExecuteResult;
import ablaze.framework.config.SystemConfig;
import ablaze.framework.exception.BaseException;
import ablaze.framework.page.PageInfo;
import ablaze.framework.web.DataController;
import com.hzd.condition.ActivityUserCondition;
import com.hzd.entity.ActivityUser;
import com.hzd.entity.RelayUser;
import com.hzd.service.ActivityService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;

/**
 * 微信授权controller
 *
 * @author kent
 * @date 15/10/19.
 */
@Controller
@RequestMapping(value = "/activity")
public class ActivityController extends DataController {

    @Autowired
    private ActivityService activityService;

    private static final Logger LOGGER = LoggerFactory.getLogger(ActivityController.class);

    //微信域名
    private static final String DOMAIN_NAME = SystemConfig.getString("wx.domain.name");

    private static final String SHARE_IMG_URL = DOMAIN_NAME + "/rent/static/img/activity/share_img.jpg";


    //------------------------------------pc端----------------------------------------
    @RequestMapping(value = "/activityUserList")
    public String activityUserList() {
        return "/activity/ActivityManager";
    }


    @RequestMapping(value = "/findActivityUserPagedList")
    @ResponseBody
    public PageInfo findActivityUserPagedList(Integer page, Integer rows, ActivityUserCondition condition) {

        return activityService.findActivityUserPagedList(page, rows, condition);
    }

    @RequestMapping(value = "/findRelayUserPagedList")
    @ResponseBody
    public PageInfo findRelayUserPagedList(Integer page, Integer rows, String fromOpenid) {

        if (isEmpty(fromOpenid)) {
            return new PageInfo();
        }

        return activityService.findRelayUserPagedList(page, rows, fromOpenid);
    }

    //------------------------------------手机端----------------------------------------

    /**
     * 活动分享授权回调接口
     *
     * @param code
     */
    @RequestMapping(value = "/oAuthCallBack")
    public String oAuthCallBack(String code) {

        if (isEmpty(code)) {

            LOGGER.info("微信授权回调未返回code");

            throw new BaseException("微信授权回调未返回code");
        }

        //分享者openId
        String openId = activityService.getOpenId(code);

        if (isEmpty(openId)) {
            LOGGER.info("获取openid失败");

            throw new BaseException("获取openid失败");
        }

        return "redirect:/activity/mainPage?openId="+openId;
    }

    /**
     * 跳转到活动主页面
     *
     * @param model
     * @return
     */
    @RequestMapping(value = "/mainPage")
    public String mainPage(String openId,Model model) {

        //String openId = (String) model.asMap().get("openId");

        ExecuteResult executeResult = activityService.main(openId);

        model.addAttribute("openId",openId);

        //已报名页面
        //String curUrl = DOMAIN_NAME + "/rent/activity/mainPage";
        String curUrl = activityService.getCurrentURL(getRequest());

        model.addAttribute("config", activityService.getJsConfig(curUrl))
                .addAttribute("shareImgUrl", SHARE_IMG_URL);

        //跳转到报名页面
        if (executeResult.isDataNotExist()) {
            //分享出去的报名授权跳转链接
            String oAthUrl = DOMAIN_NAME + "/rent/activity/oAuthCallBack";
            model.addAttribute("shareUrl", activityService.getShareUrl(oAthUrl, openId));
            return "/activity/Apply";
        }

        //分享出去的接力授权跳转链接
        String relayOAthUrl = DOMAIN_NAME + "/rent/activity/relayOAuthCallBack";
        model.addAttribute("result", executeResult.getResultData())
                .addAttribute("shareUrl", activityService.getShareUrl(relayOAthUrl, openId))
                .addAttribute("fromApplyFlag", false);   //是否刚完成报名标识

        return "/activity/Main";
    }

    /**
     * 接力页面授权回调接口
     *
     * @param code
     * @param state      传的是分享者的openId
     * @return
     */
    @RequestMapping(value = "/relayOAuthCallBack")
    public String relayOAuthCallBack(String code, String state) {

        if (isEmail(code)) {
            LOGGER.info("微信授权回调未返回code");
            throw new BaseException("微信授权回调未返回code");
        }

        return "redirect:/activity/relayPage?fromOpenId="+state + "&openId=" + activityService.getOpenId(code);
    }

    @RequestMapping(value = "/relayPage")
    public String relayPage(String fromOpenId,String openId,Model model) {

        //分享者openId
        model.addAttribute("fromOpenId",fromOpenId);
        //打开链接者的openid
        model.addAttribute("openId",openId);

        //当前页面url
        String curUrl = activityService.getCurrentURL(getRequest());
        model.addAttribute("result", activityService.main(fromOpenId).getResultData())
                .addAttribute("config", activityService.getJsConfig(curUrl))
                .addAttribute("shareImgUrl", SHARE_IMG_URL);


        //自己打开自己分享出去的链接，直接进入到自己的活动页面
        if (fromOpenId.equals(openId)) {
            //分享出去的接力授权跳转链接
            String relayOAthUrl = DOMAIN_NAME + "/rent/activity/relayOAuthCallBack";
            model.addAttribute("shareUrl", activityService.getShareUrl(relayOAthUrl, openId))
                    .addAttribute("fromApplyFlag", false);   //是否刚完成报名标识

            return "/activity/Main";
        }


        //分享出去的授权页面
        String oAthUrl = DOMAIN_NAME + "/rent/activity/relayOAuthCallBack";
        //参加活动页面
        String joinUrl = DOMAIN_NAME + "/rent/activity/oAuthCallBack";

        model.addAttribute("shareUrl", activityService.getShareUrl(oAthUrl, fromOpenId))
                .addAttribute("joinUrl", activityService.getShareUrl(joinUrl, null));

        return "/activity/Relay";
    }


    /**
     * 参加活动
     *
     * @param user
     * @return
     */
    @RequestMapping(value = "/participate")
    @ResponseBody
    public ExecuteResult participate(ActivityUser user) {

        return activityService.participate(user);
    }

    /**
     * 报名成功
     *
     * @param openId
     * @param model
     * @return
     */
    @RequestMapping(value = "/completeApply")
    public String completeApply(String openId, Model model) {

        model.addAttribute("openId",openId);

        ExecuteResult executeResult = activityService.main(openId);

        String curUrl = activityService.getCurrentURL(getRequest());
        //分享出去的授权跳转链接
        String oAthUrl = DOMAIN_NAME + "/rent/activity/relayOAuthCallBack";

        model.addAttribute("result", executeResult.getResultData())
                .addAttribute("config", activityService.getJsConfig(curUrl))
                .addAttribute("shareUrl", activityService.getShareUrl(oAthUrl, openId))
                .addAttribute("shareImgUrl", SHARE_IMG_URL)
                .addAttribute("fromApplyFlag", true);

        return "/activity/Main";
    }

    /**
     * 接力
     *
     * @return
     */
    @RequestMapping(value = "/relay")
    @ResponseBody
    public ExecuteResult relay(RelayUser user) {

        return activityService.relay(user);
    }

    /**
     * 领奖
     *
     * @param openId
     * @return
     */
    @RequestMapping(value = "/claimBond")
    @ResponseBody
    public ExecuteResult claimBond(String openId) {

        return activityService.claimBond(openId);
    }

    /**
     * 分享成功后回调
     *
     * @param user
     * @return
     */
/*    @RequestMapping(value = "/afterShare")
    @ResponseBody
    public ExecuteResult afterShare(RelayUser user) {

        return activityService.afterShare(user);
    }*/

    /**
     * 跳转到租+申请页面
     *
     * @throws IOException
     */
    @RequestMapping(value = "/applyInstalment")
    public void applyInstalment() throws IOException {

        String url = DOMAIN_NAME + "/rent/rent/applyOAthCallBack";

        getResponse().sendRedirect(activityService.getShareUrl(url, "fromAcivityFlag"));
    }
}
